package xml.hcard;

import java.io.IOException;
import java.util.List;
import org.jdom.Content;
import org.jdom.Element;
import org.jdom.filter.ElementFilter;
import org.microformats.hCard.HCard;
import org.microformats.hCard.HCardBuilder;
import org.restlet.representation.Representation;

/**
 * Classe qui permet de générer les hCards des contacts enregistrés dans la base de données du service
 * @author marya
 */
public class LocalHCARDFactory extends AbstractHCARDFactory {

    public LocalHCARDFactory(String uri, Representation representation) throws IOException {
        super(uri);
        this.document = getJDOMDocument(representation);
    }

    public HCARDFactory start() throws IOException {

        //Recupération des éléments etudiant
        List<Content> contents = (List<Content>) document.getContent(new ElementFilter("contact"));

        //Initialisation de l'élément étudiant
        Element eContact = null;
        Element eAdresse = null;
        Element email = null;
        List<Content> emails = null;
        List<Content> tels = null;
        Element tel = null;

        HCardBuilder.NameBuilder nameBuilder = HCard.Name.build();
        HCardBuilder builder = null;
        for (int i = 0; i < contents.size(); i++) {
            eContact = (Element) contents.get(i);

            //Traitement du nom
            nameBuilder.familyName(eContact.getChildText("nom"));
            nameBuilder.givenName(eContact.getChildText("prenom"));
            builder = HCard.build(eContact.getChildText("prenom") + " " + eContact.getChildText("nom"));
            builder.setN(nameBuilder.done());

            //Traitement des emails
            emails = (List<Content>) eContact.getChild("emails").getChildren();
            if (!emails.isEmpty()) {
                for (Content e : emails) {
                    email = (Element) e;
                    if (email != null) {
                        builder.addEmail(new HCard.Email(email.getValue(), email.getAttributeValue("type")));
                    }

                }
            }

            //Traitement des telephones
            tels = (List<Content>) eContact.getChild("tels").getChildren();
            if (!tels.isEmpty()) {
                for (Content t : tels) {
                    tel = (Element) t;
                    if (tel != null) {
                        builder.addTel(new HCard.Tel(tel.getValue(), tel.getAttributeValue("type")));
                    }
                }
            }
            //Rajout de l'adresse
            eAdresse = eContact.getChild("adresse");
            builder.addAdr(new HCard.Address(null, eAdresse.getChildText("voie"), null, eAdresse.getChildText("ville"), null, null, eAdresse.getChildText("codePostal"), eAdresse.getChildText("pays")));

            //Génération du hcard du contact en l'ajoutant dans la liste des hcard.
            hcards.add(builder.done());
        }
        return this;
    }
}
